#include "userdialog.h"
#include <QHBoxLayout>
#include <QMouseEvent>
#include <QGraphicsDropShadowEffect>
#include <QPainter>
#include <QPainterPath>
#include <QStyledItemDelegate>
#include <models/databasemanager.h>
#include "models/command.h"
#include "models/operatelogmodel.h"
#include<QDebug>
UserDialog::UserDialog(DialogType type, QWidget *parent)
    : PopupDialog(parent)
    , dialogType(type)
{
    setFixedSize(598*g_xScale, 400*g_xScale);
    initUI();
}

void UserDialog::initUI()
{
    setStyleSheet(QString("QWidget{background: transparent;}"
                          "QLabel {"
                          "    color: white;"
                          "    font: %1px \"微软雅黑\";"
                          "    background: transparent;}"
                          "QLineEdit, QComboBox {"
                          "    background-color: #1F1F1F;"
                          "    border: 1px solid #3E4145;"
                          "    border-radius: 0px;"
                          "    color: white;"
                          "    padding: %2px;"
                          "    font: %1px \"微软雅黑\";"
                          "}").arg(int(18*g_xScale)).arg(int(10*g_xScale)));
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(10*g_xScale, 10*g_xScale, 10*g_xScale, 10*g_xScale);
    mainLayout->setSpacing(0);

    // 添加自定义标题栏
    QWidget *titleBar = new QWidget;
    titleBar->setFixedHeight(50*g_xScale);
    titleBar->setStyleSheet(QString(
                                "QWidget {"
                                "    background: transparent;"
                                "    border-top-left-radius: %1px;"
                                "    border-top-right-radius: %1px;"
                                "}").arg(int(15*g_xScale)));

    QHBoxLayout *titleLayout = new QHBoxLayout(titleBar);
    titleLayout->setContentsMargins(20*g_xScale, 0, 10*g_xScale, 0);

    titleLabel = new QLabel(dialogType == Add ? "新建用户" : "编辑用户");
    titleLabel->setStyleSheet(QString(
                                  "QLabel {"
                                  "    color: white;"
                                  "    font: %1px \"微软雅黑\";"
                                  "    background: transparent;" "}").arg(int(20*g_xScale)));

    closeButton = new TouchButton();
    closeButton->setFixedSize(40*g_xScale, 40*g_xScale);
    closeButton->setStyleSheet(
        "QPushButton{"
        "   background-image: url(:/images/close.png);"
        "   background-color:transparent;"
        "   background-repeat:no-repeat;"
        "   background-position:center;"
        "    border-radius: 0px;}"
        "QPushButton:pressed{"
        "background-color: rgb(255, 0, 0);"
        "}"
        );

    titleLayout->addWidget(titleLabel);
    titleLayout->addStretch();
    titleLayout->addWidget(closeButton);

    // 内容区域容器
    QWidget *contentWidget = new QWidget;
    QVBoxLayout *contentLayout = new QVBoxLayout(contentWidget);
    contentLayout->setContentsMargins(44, 20, 44, 20);
    contentLayout->setSpacing(0);

    // 权限选择（水平布局）
    QHBoxLayout *roleLayout = new QHBoxLayout;
    roleLayout->setSpacing(5);
    QLabel *roleLabel = new QLabel("用户权限：");
    roleLabel->setFixedWidth(80*g_xScale);
    roleComboBox = new QComboBox;
    QListView *view = new QListView(roleComboBox);
    view->setStyleSheet(QString("QListView { scrollbar-width: 0px; }"
                                "QListView::item { height: %1px; }").arg(int(30*g_xScale)));
    roleComboBox->setView(view);
    view->setItemDelegate(new QStyledItemDelegate(this));
    view->setFixedHeight(58*g_xScale);  // 设置列表视图的高度

    roleComboBox->setFixedSize(410*g_xScale, 50*g_xScale);
    roleComboBox->setStyleSheet(QString(
                                    "QComboBox {"
                                    "    padding-left: %1px;"
                                    "    background-color: #1F1F1F;"
                                    "    border: 1px solid #3E4145;"
                                    "    color: white;"
                                    "    font: %2px \"微软雅黑\";"
                                    "}"
                                    "QComboBox::drop-down {"
                                    "    border: none;"
                                    "    padding-right: %1px;"
                                    "    width: %3px;"
                                    "}"
                                    "QComboBox::down-arrow {"
                                    "    image: url(:/images/combox_drop.png);"
                                    "}"
                                    "QComboBox QAbstractItemView {"
                                    "    background-color: #1F1F1F;"
                                    "    border: 1px solid #3E4145;"
                                    "    selection-background-color: #4A90E2;"
                                    "    color: white;"
                                    "    font: %2px \"微软雅黑\";"
                                    "    padding-left: %1px;"
                                    "}"
                                    "QComboBox QAbstractItemView::item:hover {"
                                    "    background-color: #357ABD;"
                                    "}").arg(int(10*g_xScale)).arg(int(18*g_xScale)).arg(int(30*g_xScale)));
    roleComboBox->addItem("开发者");
    roleComboBox->addItem("普通用户");
    roleLayout->addWidget(roleLabel);
    roleLayout->addWidget(roleComboBox);
    roleLayout->addStretch();

    // 用户名输入（水平布局）
    QHBoxLayout *nameLayout = new QHBoxLayout;
    nameLayout->setSpacing(5);
    QLabel *nameLabel = new QLabel("用户名：");
    nameLabel->setFixedWidth(80*g_xScale);
    nameLabel->setStyleSheet("background: transparent;");
    nameEdit = new QLineEdit;
    nameEdit->setFixedSize(410*g_xScale, 50*g_xScale);
    nameEdit->setValidator(new QRegExpValidator(QRegExp("[\u4e00-\u9fa5a-zA-Z0-9]+"), this));
    nameLayout->addWidget(nameLabel);
    nameLayout->addWidget(nameEdit);
    nameLayout->addStretch();
    
    // 密码输入（水平布局）
    QHBoxLayout *passwordLayout = new QHBoxLayout;
    passwordLayout->setSpacing(5*g_xScale);
    QLabel *passwordLabel = new QLabel("密码：");
    passwordLabel->setFixedWidth(80*g_xScale);
    passwordLabel->setStyleSheet("background: transparent;");
    passwordEdit = new QLineEdit;
    passwordEdit->setFixedSize(410*g_xScale, 50*g_xScale);
    passwordEdit->setEchoMode(QLineEdit::Password);
    connect(passwordEdit,&QLineEdit::textEdited,this,&UserDialog::textChanged,Qt::UniqueConnection);
    passwordLayout->addWidget(passwordLabel);
    passwordLayout->addWidget(passwordEdit);
    passwordLayout->addStretch();
    


    // 按钮区域
    QWidget *btnContainer = new QWidget;
    btnContainer->setFixedSize(500*g_xScale,50*g_xScale);
    //btnContainer->setStyleSheet("background: #ff255252;");
    //btnContainer->setStyleSheet("background: transparent;");
    QHBoxLayout *btnContainerLayout = new QHBoxLayout(btnContainer);
    btnContainerLayout->setContentsMargins(0, 0, 0, 0);
    btnContainerLayout->setSpacing(30*g_xScale);
    
    TouchButton *confirmBtn = new TouchButton("确定");
    TouchButton *cancelBtn = new TouchButton("取消");
    
    confirmBtn->setFixedSize(120*g_xScale, 50*g_xScale);
    cancelBtn->setFixedSize(120*g_xScale, 50*g_xScale);
    
    QString style= QString("QPushButton {"
                            "    background-color: #007BFF;"
                            "    color: white;"
                            "    border-radius: %1px;"
                            "    padding: 0px;"
                            "    font: %2px \"微软雅黑\";"
                            "    margin: 0px 10px 0px 0px;"
                            "}"
                            "QPushButton:pressed {"
                            "    background-color: #0056b3;"
                            "}").arg(int(5*g_xScale)).arg(int(20*g_xScale));
    // 设置确定按钮样式
    confirmBtn->setStyleSheet(style);
    // 设置取消按钮样式
    cancelBtn->setStyleSheet(style);

    //错误处理
    nameLayout->setSpacing(5);
    errLabel = new QLabel(strError);
    errLabel->setFixedWidth(520);
    errLabel->setStyleSheet(QString("background: transparent;color:red;font: %1px \"微软雅黑\";").arg(int(16*g_xScale)));
    errLabel->setAlignment(Qt::AlignCenter);
    btnContainerLayout->addStretch();
    btnContainerLayout->addWidget(confirmBtn);
    btnContainerLayout->addWidget(cancelBtn);
    btnContainerLayout->addStretch();
    // 将所有布局添加到主布局
    contentLayout->addLayout(roleLayout);
    contentLayout->addSpacing(20);
    contentLayout->addLayout(nameLayout);
    contentLayout->addSpacing(20);
    contentLayout->addLayout(passwordLayout);
    contentLayout->addSpacing(5);
    contentLayout->addWidget(errLabel);
    contentLayout->addSpacing(5);
    contentLayout->addWidget(btnContainer);
    contentLayout->addStretch();
    mainLayout->addWidget(titleBar);
    mainLayout->addWidget(contentWidget);

    // 连接按钮信号
    connect(confirmBtn, &QPushButton::clicked, this, &UserDialog::accept);
    connect(cancelBtn, &QPushButton::clicked, this, &QDialog::reject);
    // 连接关闭按钮信号
    connect(closeButton, &QPushButton::clicked, this, &UserDialog::reject);
}



void UserDialog::accept()
{
    if(nameEdit->text().isEmpty())
    {  if(errLabel)
            errLabel->setText("用户名不能为空！");
        return;
    }
    else if(passwordEdit->text().isEmpty())
    {  if(errLabel)
            errLabel->setText("密码不能为空！");
        return;
    }
    if(dialogType==Add)
    {
        QString strErr;
        UserInfo userinfo;
        userinfo.nPermission=roleComboBox->currentIndex();
        userinfo.userName=nameEdit->text();
        userinfo.userPwd=passwordEdit->text();
        if(DatabaseManager::getInstance()->addUser(
                userinfo,strErr))
        {
            OPERATE_LOG(tr("添加用户\"%1\"").arg(nameEdit->text()));
        }
        else
        {
            errLabel->setText(strErr);
            qDebug()<<tr("添加用户\"%1\"失败！").arg(nameEdit->text())<<strErr;
            return;
        }
    }
    else
    {
        QString strErr;
        QString pwd=passwordEdit->text();
        if(!bPwdTextIsChanged)//如果没有改变密码则数据库不更改密码
            pwd="";
        UserInfo userinfo;
        userinfo.nPermission=roleComboBox->currentIndex();
        userinfo.userName=nameEdit->text();
        userinfo.userPwd=passwordEdit->text();
        if(DatabaseManager::getInstance()->editUser(
                userinfo,strOldUserName,strErr))
        {
            OPERATE_LOG(tr("编辑用户\"%1\"成功！").arg(nameEdit->text()));
        }
        else
        {
            errLabel->setText(strErr);
            qDebug()<<tr("编辑用户\"%1\"失败！").arg(nameEdit->text())<<strErr;
            return;
        }
    }

    QDialog::accept();
}

void UserDialog::setUserData(const QString &name, UserRole role, const QString &password)
{
    strOldUserName= name;
    nameEdit->setText(name);
    passwordEdit->setText(password);
    roleComboBox->setCurrentIndex(static_cast<int>(role));
}

void UserDialog::setError(QString strErr)
{
    strError = strErr;
}

void UserDialog::textChanged(const QString &strText)
{
    Q_UNUSED(strText);
    bPwdTextIsChanged=true;
}
